package com.demo.androidtv.services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.demo.androidtv.utils.WebSocketTool;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by Corolin on 17-7-4.
 */

public class WebSocketServerService extends Service {
    private Server server;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getGPRSLocalIpAddress();
        server = new Server();
        server.start();
    }

    public static void getGPRSLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        Log.d("Service", inetAddress.getHostAddress());
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("Service", "WifiPreference IpAddress", ex);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class Server extends WebSocketServer {
        private List<WebSocket> clients = new ArrayList<>();

        Server() {
            super(new InetSocketAddress(3001));
        }

        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            clients.add(conn);
        }

        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            clients.remove(conn);
        }

        @Override
        public void onMessage(WebSocket conn, String message) {
            for (WebSocket client : clients) {
                client.send(message);
            }
        }

        @Override
        public void onError(WebSocket conn, Exception ex) {

        }

        @Override
        public void onStart() {
        }
    }
}
